import time

from aip import AipOcr
from PIL import Image
import pytesseract
from selenium import webdriver


# 存储验证码截图
def save_img(driver):
    driver.save_screenshot('page.png')  # 截图
    code_img_ele = driver.find_element_by_xpath('//*[@class="verify_header"]/img')  # 要验证的图片验证码
    location = code_img_ele.location  # 验证码左上角的坐标x,y
    size = code_img_ele.size  # 验证码对应的长和宽
    # 得到左上角和右下角的坐标
    # left, top, right, height

    rangle = (
        int(location['x']), int(location['y']), int((location['x'] + size['width'])),
        int((location['y'] + size['height']))
    )
    # print(rangle)
    image1 = Image.open('./page.png')
    # code_img_name = './code.png'
    # crop根据rangle元组内的坐标进行裁剪 裁剪出验证码区域
    frame = image1.crop((rangle))
    frame.save('./code.png')
    # gray = im.convert('L')
    # bw = gray.point(lambda x: 0 if x < 140 else 255, '1')  # 如果RGB数值小于140的变成1，否则是255。也就是将验证码背景变成白色，具体字符变成黑色。
    # bw.save('./code.png')

    return code_img_ele


# 方法一百度识别
def baiduOCR(picfile):  # picfile:图片文件名   对验证码图片进行OCR识别
    APP_ID = '26478267 '  # 这是你产品服务的appid
    API_KEY = 'QUz17sPVOkl5ZC9XRlTwZ0Nx '  # 这是你产品服务的appkey
    SECRET_KEY = ' b6C6A6kFGsC0AyjfTV4hBOkdt4v8GAmN'  # 这是你产品服务的secretkey
    client = AipOcr(APP_ID, API_KEY, SECRET_KEY)
    i = open(picfile, 'rb')
    img = i.read()
    message = client.basicAccurate(img)
    i.close()
    print('百度的识别出来的', message['words_result'])
    return message['words_result']


# 执行登录及调用
def login():
    driver = webdriver.Chrome()
    driver.get('https://dxt.yayi360.com/#/')
    driver.maximize_window()
    driver.find_element_by_xpath("//div[@placeholder='请输入手机号']/input").send_keys("13212121212")
    driver.find_element_by_xpath("//div[@placeholder='请输入密码']/input").send_keys("123123")
    driver.find_element_by_class_name("zh_postForm").click()
    try:
        driver.find_element_by_xpath('//*[text()="登录成功"]')
        time.sleep(2)
        driver.quit()
        print('不需要验证码登录成功')
    except:
        time.sleep(5)
        print("跳转验证码校验")
        try:
            # 保存页面截图，并根据坐标裁剪获取验证码图片
            code_img_ele = save_img(driver)
            baiduOCR('code.png')  # 提取验证码文字
        except Exception as e:
            driver.quit()
            raise e


# 调试使用
login()
baiduOCR('code.png')  # 百度的提取验证码文字

im = Image.open('code.png')
string2 = pytesseract.image_to_string(im, lang="chi_sim")
print('pytesseract提取的-------', string2)

